/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model.util;

import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletContext;
import org.apache.log4j.Logger;

/**
 *
 * @author PhucAn
 */
public class MailUtil {

    static Logger log = Logger.getLogger(MailUtil.class);

    public int send(String smtpServer, String smtpPort, String to, String from, String psw,
            String subject, String body) {

        try {
            Properties props = System.getProperties();
            props.put("mail.smtp.host", smtpServer);
            props.put("mail.smtp.port", smtpPort);//587
            props.put("mail.smtp.starttls.enable", "true");
            final String login = from;//usermail
            final String pwd = psw;//"password cua ban o day";
            Authenticator pa = null; //default: no authentication
            if (login != null && pwd != null) { //authentication required?
                props.put("mail.smtp.auth", "true");
                pa = new Authenticator() {

                    @Override
                    public PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(login, pwd);
                    }
                };
            }//else: no authentication
            Session session = Session.getInstance(props, pa);
// — Create a new message –
            Message msg = new MimeMessage(session);
// — Set the FROM and TO fields –
            msg.setFrom(new InternetAddress(from));
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(
                    to, false));

// — Set the subject and body text –
            msg.setSubject(subject);
            msg.setContent(body, "text/html");
// — Set some other header information –
            msg.setHeader("X-Mailer", "LOTONtechEmail");
            msg.setSentDate(new Date());
            msg.saveChanges();
// — Send the message –
            Transport.send(msg);
            log.info("Message is sent to " + to);
        } catch (MessagingException ex) {
            log.info("Message cannot be sent to " + to + ". " + ex.getMessage());
            return 0;
        } catch (Exception ex) {
            log.info(ex.getMessage());
            return 0;
        }
        return 1;
    }

    /**
     * Send mail using information from a servlet context
     * @param context
     * @param to
     * @param subject
     * @param body 
     */
    public  int send(ServletContext context, String to, String subject, String body) {
        String smtpServer = context.getAttribute(SharingUtil.VAR_A_MAIL_SERVER).toString();
        String smtpPort = context.getAttribute(SharingUtil.VAR_A_MAIL_PORT).toString();
        String mailUser = context.getAttribute(SharingUtil.VAR_A_MAIL_USER_ID).toString();
        String mailPassword = context.getAttribute(SharingUtil.VAR_A_MAIL_PASSWORD).toString();
        return send(smtpServer, smtpPort, to, mailUser, mailPassword, subject, body);
    }
    public static void main(String[] args) {
        {
            try {
                MailUtil mailer=new MailUtil();
                String smtpServer = "smtp.gmail.com";
                String smtpPort = "587";
                String to = "nphucan17@gmail.com";
                String from = "littlecatdevil@gmail.com";
                String subject = "Hello from Java";
                String body = "<html><head></head><body><h1>Test java mail</h1><br/><b>This is my email</b></body></html>";
                String password = "";
               int i= mailer.send(smtpServer, smtpPort, to, from, password, subject, body);
                System.out.println("Finish! - "+i);
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }

        }
    
  }
}
